package offer;

import java.util.ArrayList;

//顺时针打印矩阵
public class T20 {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
          int l=0;
          int r=matrix[0].length-1;
          int u = 0;
          int d=matrix.length-1;
        ArrayList<Integer> list = new ArrayList<Integer>();
          while (l<=r&&u<=d) {
              for (int i = l;i<=r;i++) {
                  list.add(matrix[u][i]);
              }
              u++;
              if (u>d) break;
              for (int i = u; i <= d; i++) {
                  list.add(matrix[i][r]);
              }

              r--;
              if (l>r) break;
              for (int i = r; i>= l; i--) {
                  list.add(matrix[d][i]);
              }
              d--;
              if (u>d) break;
              for (int i = d; i >= u ; i--) {
                  list.add(matrix[i][l]);
              }
              l++;
          }
          return list;
    }
    public static void main ( String[] args) {
        /*
                {1,2,3,4},
                {5,6,7,8},
                {9,10,11,12},
                {13,14,15,16}
         */
        int array[][] = new int[][] {
                {1},{2},{3},{4},{5}
        };
        System.out.println(new T20().printMatrix(array));
    }
}
